﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _80X_CG_Frame.Utils
{
    /// <summary>
    /// 配置文件类
    /// </summary>
    public class ConfigUtil
    {
        public JObject configs = new JObject();
        private string config_path;
        /// <summary>
        /// 构造函数
        /// </summary>
        public ConfigUtil()
        {
        }
        /// <summary>
        /// 带配置文件路径的构造函数
        /// </summary>
        /// <param name="_config_path"></param>
        public ConfigUtil(string _config_path)
        {
            config_path = _config_path;
        }

        /// <summary>
        /// 读配置,如果出现异常则打印日志
        /// </summary>
        /// <returns>错误信息</returns>
        public string ReadConfig()
        {
            string err = "";
            try
            {
                using (StreamReader reader = File.OpenText(config_path))
                {
                    configs = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
                }
            }
            catch (System.Exception ex)
            {
                err = ex.Message;
                return err;
            }
            return err;
        }

        /// <summary>
        /// 传入配置文件并读配置
        /// </summary>
        /// <param name="full_path"></param>
        /// <returns></returns>
        public string ReadConfig(string full_path)
        {
            string err = "";
            config_path = full_path;
            try
            {
                using (StreamReader reader = File.OpenText(config_path))
                {
                    configs = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
                }
            }
            catch (System.Exception ex)
            {
                err = ex.Message;
                return err;
            }
            return err;
        }
        /// <summary>
        /// 写入配置
        /// </summary>
        public void WriteConfig()
        {
            File.WriteAllText(config_path, configs.ToString());
        }
        /// <summary>
        /// 带路径的写入配置
        /// </summary>
        /// <param name="new_path"></param>
        public void WriteConfig(string new_path)
        {
            config_path = new_path;
            File.WriteAllText(config_path, configs.ToString());
        }

        /// <summary>
        /// 取得配置项
        /// </summary>
        /// <param name="name">配置名</param>
        /// <returns>配置(字符串)</returns>
        public string Get(string name)
        {
            return (string)configs[name];
        }
        /// <summary>
        /// 设置配置项
        /// </summary>
        /// <param name="name">配置名</param>
        /// <param name="value">设置的参数</param>
        public void Set(string name, string value)
        {
            configs[name] = value;
        }
    }
}
